
import 'package:flutter/material.dart';
import 'package:flutter_app/counter/counter_keybord.dart';
import 'package:flutter_app/openeye/utils/toast_utils.dart';
import 'package:flutter_app/openeye/widget/app_bar.dart';

class Counter extends StatefulWidget {
  const Counter({Key? key}) : super(key: key);

  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  final StringBuffer _result = StringBuffer("");
  final StringBuffer _beforeText = StringBuffer("");
  String _operateText = "";
  bool _isFirstNum = true; //是否记录的第一个数字

  @override
  Widget build(BuildContext context) {
    return materialPage(
        appBar: appBar("计算器页面"),
        page: Container(
          padding: const EdgeInsets.symmetric(horizontal: 18),
          child: createCounterPage(),
        ));
  }

  createCounterPage() {
    return Column(
      children: [
        createShowResult(),
        const SizedBox(
          height: 20,
        ),
        CounterKeyBord(onValueChange: (value) {
          inputInfo(value);
        }),
        const SizedBox(
          height: 80,
        )
      ],
    );
  }

  createShowResult() {
    return Expanded(
      child: Container(
        alignment: Alignment.bottomRight,
        child: Text(
          _isFirstNum?_result.toString():_beforeText.toString(),
          maxLines: 1,
          style: const TextStyle(fontSize: 48, fontWeight: FontWeight.w400),
        ),
      ),
    );
  }

  void inputInfo(String value) {
    switch (value) {
      case "+":
      case "-":
      case "X":
      case "÷":
      case "%":
        _operateText = value;
        _isFirstNum = false;
        break;
      case "=":
        compute();
        break;
      case "+/-":
        //取反
        break;
      case "AC":
        clearNum();
        _result.write("0");
        setState(() {});
        break;
      case ".":
        recordData(value);
        break;
      default:
        {
          recordData(value);
        }
        break;
    }
  }
  //计算方法
  void compute() {
    if(_operateText.isEmpty){
      ToastUtils.showTip("输入有误");
      return;
    }

    var result = double.parse(_result.toString());
    var before = double.parse(_beforeText.toString());

    switch (_operateText){
      case "+":
        result+=before;
        break;
      case "-":
        result-=before;
        break;
      case "X":
        result*=before;
        break;
      case "÷":
        result/=before;
        break;
      case "%":
        result/=before;
        ToastUtils.showTip("未实现");
        break;
    }
    clearNum();
    _result.write(result);
    setState(() {});
  }

  void recordData(String value) {
    if (_isFirstNum) {
      _result.write(value);
    } else {
      _beforeText.write(value);
    }
    setState(() {});
  }

  void clearNum() {
    _result.clear();
    _beforeText.clear();
    _isFirstNum = true;
    _operateText = "";
  }
}
